<?php


namespace App\Web\Controller;

use App\Web\Model\Message as MessageModel;
use EchoPHP\Http\Request;

class Message extends Controller {

    /**
     * 获取消息列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function messageList(Request $request) {
        $lastId = $request->getParam('lastid', 0);
        $type = $request->getParam('type', MessageModel::MSG_TYPE_HANDLE);
        $readStatus = $request->getParam('readstatus', 'all');
        $loginId = $this->getLoginId();
        $messageModel = new MessageModel();
        $messageList = $messageModel->getMessageList($loginId, $lastId, $type, $readStatus);
        return $this->json(['status' => true, 'message' => '获取成功', 'list' => $messageList]);
    }

    /**
     * 更新单条消息已读状态
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function readMessage(Request $request) {
        $messageId = $request->getParam('messageid', 0);
        $loginId = $this->getLoginId();

        $messageModel = new MessageModel();
        $result = $messageModel->handleReadStatus($loginId, [$messageId]);
        return $this->json(['status' => $result, 'message' => $result ? '操作成功' : '操作失败']);
    }

    /**
     * 批量更新未读消息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function batchReadMessage(Request $request) {
        $messageIds = $request->getParam('messageids', 0);
        $loginId = $this->getLoginId();
        $messageIds = explode(',', $messageIds);
        if (count($messageIds) > 20) {
            return $this->json(['status' => false, 'message' => '单次批量更新最多20条']);
        }

        $messageModel = new MessageModel();
        $result = $messageModel->handleReadStatus($loginId, $messageIds);
        return $this->json(['status' => $result, 'message' => $result ? '操作成功' : '操作失败']);
    }

    /**
     * 批量更新全部消息状态
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function readAllMessage(Request $request) {
        $type = $request->getParam('type', MessageModel::MSG_TYPE_HANDLE);
        $loginId = $this->getLoginId();

        $messageModel = new MessageModel();
        $result = $messageModel->handleAllReadStatus($loginId, $type);
        return $this->json(['status' => $result, 'message' => $result ? '操作成功' : '操作失败']);
    }
}